<template>
  <el-dialog :visible.sync="permissionsDialogVisible" width="700px" :before-close="close">
    <template #title>
      <span>权限列表</span>
      <span style="color: red;font-size: small"> (此处仅限查看，如需更改请进行角色权限设置)</span>
    </template>
    <el-tree
      ref="permissions"
      :data="permissionsData"
      :default-checked-keys="permissionsIDs"
      :props="defaultProps"
      check-strictly
      accordion
      show-checkbox
      node-key="id"
    />
  </el-dialog>
</template>
<script>
import { getPermissions } from '@/api/system/permissions'
import { getUserPermissions } from '@/api/system/users'

export default {
  name: 'PermissionsDialog',
  props: {
    permissionsDialogVisible: {
      type: Boolean,
      default: false
    },
    userID: {
      type: Number,
      default: null
    }
  },

  data() {
    return {
      permissionsData: [],
      permissionsIDs: [],
      defaultProps: { children: 'children', label: 'label' }
    }
  },
  watch: {
    permissionsDialogVisible(v) {
      if (v) {
        if (this.userID) {
          getPermissions({ getType: 'tree' }).then(res => {
            this.permissionsData = res.data
            this.changeDisabled(this.permissionsData, true)
          })
          getUserPermissions(this.userID).then(res => {
            this.permissionsIDs = res.data
          })
        }
      }
    }
  },
  methods: {
    close() {
      this.permissionsIDs = []
      this.permissionsData = []
      this.$emit('permissionsClose')
    },
    // 更改Permissions Tree的disabled属性
    changeDisabled(data, disabled) {
      if (data?.length < 1) {
        return false
      }
      for (let index = 0; index < data.length; index++) {
        const children = data[index].children
        if (children) {
          this.changeDisabled(children, disabled)
        }
        data[index].disabled = disabled
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
